/**
 * @description form表单的校验规则
 */
import isMobilePhone from 'validator/lib/isMobilePhone'
import isIdentityCard from 'validator/lib/isIdentityCard'
import isEmail from 'validator/lib/isEmail'

/**
 * @description 多个字段翻译拼接的段落
 */
export const zhAndEnShowMsg = function () {
  const arr = Array.prototype.slice.call(arguments)
  return localStorage.getItem('language') === 'en'
    ? arr.join('\t')
    : arr.join('')
}

/**
 * 公共文本输入框的校验
 * 非空限制
 * @param {*} label
 * @returns Object
 */
export const commonInputText = (label = '', required = true) => {
  return [
    {
      required,
      message: () => zhAndEnShowMsg(g_t('public.pleaseInput'), label),
      trigger: ['blur', 'change']
    }
  ]
}

// 通用单行文本输入框的校验
export const singleLineText = (label = '') => {
  return [
    ...commonInputText(label),
    {
      pattern: /^[\u4e00-\u9fa5a-zA-Z0-9-_]{1,128}$/,
      message: () => g_t('rule.chineseLetterNumTips', { max: 128 }),
      trigger: ['blur', 'change']
    }
  ]
}

// 多行文本输入框的校验
export const multilineText = (label = '') => {
  return [
    ...commonInputText(label),
    {
      pattern: /^.{1,128}$/,
      message: () => g_t('rule.charLimitTips', { max: 128 }),
      trigger: ['blur', 'change']
    }
  ]
}

// 下拉框的校验
export const selectRule = (label = '') => {
  return [
    {
      required: true,
      message: () => zhAndEnShowMsg(g_t('public.pleaseSelect'), label),
      trigger: ['blur', 'change']
    }
  ]
}

// 上传文件的校验
export const uploadFileRule = (label = '') => {
  return [
    {
      required: true,
      message: () => zhAndEnShowMsg(g_t('public.pleaseUpload'), label),
      trigger: 'change'
    }
  ]
}

// 创建数字类型验证规则工厂
const createNumberRule = (label, errorMsg, required = true) => [
  ...commonInputText(label, required),
  {
    pattern: /^[1-9]\d*$/,
    message: () => errorMsg,
    trigger: ['blur', 'change']
  }
]

// 创建数字或小数点类型验证规则工厂
const createDecimalRule = (label, errorMsg, required = true) => [
  ...commonInputText(label, required),
  {
    // 只能输入正整数或者小数，不能以0开头的正整数，可以是一个0开头的小数，不能是一个0，不能只输入空字符串或多个空字符串
    // pattern: /^(0|[1-9]\d*)(\.\d+)?$/,
    pattern:
      /^(?!0$)(?!0\d)(?!0\.0$)(?!\s*$)([1-9]\d*(\.\d+)?|0\.\d*[1-9]\d*)$/,
    message: () => errorMsg,
    trigger: ['blur', 'change']
  }
]

// 创建零或数字或小数点类型验证规则工厂
const createDecimalRule2 = (label, errorMsg, required = true) => [
  ...commonInputText(label, required),
  {
    // 只能输入正整数或者小数，不能以0开头的正整数，可以是一个0开头的小数，可以输入一个0，不能只输入空字符串或多个空字符串
    pattern: /^(0|[1-9]\d*)(\.\d*[1-9]\d*|(\.0+)?)$/,
    message: () => errorMsg,
    trigger: ['blur', 'change']
  }
]

// 创建允许负数、零或正数的验证规则工厂
const createSignedDecimalRule = (label, errorMsg, required = true) => [
  ...commonInputText(label, required),
  {
    // 允许负数、零或正数（可以是整数或小数）
    pattern: /^(-?(0|[1-9]\d*)(\.\d*[1-9]\d*|(\.0+)?)|0)$/,
    message: () => errorMsg,
    trigger: ['blur', 'change']
  }
]

// 车牌号
export const licensePlate = [
  ...commonInputText(g_t('fleet.licensePlate')),
  {
    // pattern:
    //   /^([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-HJ-NP-Z][A-HJ-NP-Z0-9]{4,5}[A-HJ-NP-Z0-9挂学警港澳]|[A-Z0-9]{2,8})$/,
    // pattern: /^\S{2,8}$/,
    pattern: /^[\u4e00-\u9fa5A-Z0-9\/]{2,32}$/,
    message: () => g_t('rule.validateLicensePlate'),
    trigger: ['blur', 'change']
  }
]

// 年龄
export const age = [
  ...commonInputText(g_t('fleet.age')),
  {
    pattern: /^(1[89]|[2-5]\d|60)$/,
    message: () => g_t('rule.validateAge'),
    trigger: ['blur', 'change']
  }
]

// 年龄
export const startAge = (formData, key, refForm) => {
  return [
    ...commonInputText(g_t('travelAgency.applicableAge')),
    {
      pattern: /^(0|([1-9]\d?)|(1[01]\d?)|120)$/,
      validator(rule, value, callback) {
        // console.log(rule, value, formData[key])
        if (!rule.pattern.test(value)) {
          callback(new Error(g_t('rule.validateAge2')))
        } else if (formData[key] && value > formData[key] * 1) {
          callback(new Error(g_t('rule.validateMinAgeThanMaxAge')))
        } else if (formData[key] && value <= formData[key] * 1) {
          refForm.value.clearValidate(key)
          callback()
        } else {
          callback()
        }
      },
      trigger: ['blur', 'change']
    }
  ]
}

// 年龄
export const endAge = (formData, key, refForm) => {
  return [
    ...commonInputText(g_t('travelAgency.applicableAge')),
    {
      pattern: /^(0|([1-9]\d?)|(1[01]\d?)|120)$/,
      validator(rule, value, callback) {
        // console.log(rule, value, formData[key])
        if (!rule.pattern.test(value)) {
          callback(new Error(g_t('rule.validateAge2')))
        } else if (formData[key] && value < formData[key] * 1) {
          callback(new Error(g_t('rule.validateMaxAgeThanMinAge')))
        } else if (formData[key] && value >= formData[key] * 1) {
          refForm.value.clearValidate(key)
          callback()
        } else {
          callback()
        }
      },
      trigger: ['blur', 'change']
    }
  ]
}

// 联系电话
export const phone = ({
  label = g_t('public.phone'),
  required = true
} = {}) => {
  return [
    ...commonInputText(label, required),
    {
      required,
      validator(rule, value, callback) {
        // 没填不需要校验，填了需校验
        if (!rule.required && !value.length) {
          callback()
        } else if (isMobilePhone(value, 'zh-CN')) {
          callback()
        } else {
          callback(new Error(g_t('rule.validatePhone')))
        }
      },
      trigger: ['blur', 'change']
    }
  ]
}

// 车辆费用
export const vehicleCost = createDecimalRule(
  g_t('fleet.vehicleCost'),
  g_t('rule.validateVehicleCost'),
  false
)

// 身份证号
export const idCard = ({ required = true } = {}) => {
  return [
    ...commonInputText(g_t('fleet.idCard'), required),
    {
      validator(rule, value, callback) {
        // 没填不需要校验，填了需校验
        if (!rule.required && !value.length) {
          callback()
        } else if (isIdentityCard(value, 'zh-CN')) {
          callback()
        } else {
          callback(new Error(g_t('rule.validateIdCard')))
        }
      },
      trigger: ['blur', 'change']
    }
  ]
}

// 用户名
export const userName = [
  ...commonInputText(g_t('public.userName')),
  {
    pattern: /^\w{1,30}$/,
    message: () => g_t('rule.letterNumTips', { max: 30 }),
    trigger: ['blur', 'change']
  }
]

// 邮箱
export const email = ({
  label = g_t('public.email'),
  required = true
} = {}) => {
  return [
    ...commonInputText(label, required),
    {
      required,
      validator(rule, value, callback) {
        // 没填不需要校验，填了需校验
        if (!rule.required && !value.length) {
          callback()
        } else if (isEmail(value)) {
          callback()
        } else {
          callback(new Error(g_t('rule.validateEmail')))
        }
      },
      trigger: ['blur', 'change']
    }
  ]
}

// 密码
export const password = [
  ...commonInputText(g_t('public.password')),
  {
    validator(rule, value, callback) {
      // 须包含字母、数字，可以有特殊字符
      const pwdRegex =
        /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d!@#$%^&*()_+\-=\[\]{};:'",./<>?]{8,30}$/
      if (pwdRegex.test(value)) {
        callback()
      } else {
        callback(new Error(g_t('rule.passwordRequire', { min: 8, max: 30 })))
      }
    },
    trigger: ['blur', 'change']
  }
]

// 确认密码
export const confirmPassword = (formData, key) => {
  return [
    ...commonInputText(g_t('public.confirmPassword')),
    {
      validator(rule, value, callback) {
        if (formData[key] === value) {
          callback()
        } else {
          callback(new Error(g_t('rule.confirmPassword')))
        }
      },
      trigger: ['blur', 'change']
    }
  ]
}

// 行程天数
export const travelDays = createNumberRule(
  g_t('fleet.travelDays'),
  g_t('rule.validTravelDays'),
  false
)

// 行程里程
export const travelDistance = ({ required = true }) => {
  return createDecimalRule(
    g_t('fleet.travelDistance'),
    g_t('rule.validTravelMileage'),
    required
  )
}

// 行程人数
export const travelerCount = createNumberRule(
  g_t('fleet.travelerCount'),
  g_t('rule.validTravelPeople')
)

// 客户预算
export const customerBudget = createDecimalRule(
  g_t('fleet.quotePrice'),
  g_t('rule.validQuotePrice'),
  false
)

// 成本费用
export const costExpense = createDecimalRule(
  g_t('fleet.costExpense'),
  g_t('rule.validCost')
)

// 订单利润
export const orderProfit = createDecimalRule(
  g_t('fleet.orderProfit'),
  g_t('rule.validOrderProfit'),
  false
)

// 房间楼层
export const roomFloor = createNumberRule(
  g_t('hotel.roomFloor'),
  g_t('rule.validRoomFloor')
)

// 房间面积
export const roomArea = createDecimalRule(
  g_t('hotel.roomArea'),
  g_t('rule.validRoomArea')
)

// 可住人数
export const maxOccupancy = createNumberRule(
  g_t('hotel.maxOccupancy'),
  g_t('rule.validMaxOccupancy')
)

// 单价
export const unitPrice = createDecimalRule(
  g_t('hotel.unitPrice'),
  g_t('rule.validUnitPrice')
)

export const unitPriceNum = createSignedDecimalRule(
  g_t('hotel.unitPrice'),
  g_t('rule.validUnitPrice')
)

// 人数
export const personCount = createNumberRule(
  g_t('hotel.personCount'),
  g_t('rule.validPersonCount')
)

// 金额
export const amount = createDecimalRule(
  g_t('hotel.amount'),
  g_t('rule.validAmount')
)

// 金额
export const amount2 = createDecimalRule2(
  g_t('hotel.amount'),
  g_t('rule.validAmount')
)

// 价格
export const price = ({ required = true }) => {
  return createDecimalRule2(
    g_t('travelAgency.price'),
    g_t('rule.validPrice'),
    required
  )
}

// 线路数量
export const routeQuantity = createNumberRule(
  g_t('travelAgency.routeQuantity'),
  g_t('rule.validMaxOccupancy')
)

// 天数
export const days = createNumberRule(
  g_t('travelAgency.days'),
  g_t('rule.validDays')
)

// 住宿晚数
export const accommodationNights = createNumberRule(
  g_t('travelAgency.accommodationNights'),
  g_t('rule.validAccNights')
)

// 成团人数
export const groupFormingNumber = createNumberRule(
  g_t('travelAgency.groupFormingNumber'),
  g_t('rule.validGroupNumber')
)

// 出团天数
export const departureDays = createNumberRule(
  g_t('travelAgency.departureDays'),
  g_t('rule.validDepartureDays')
)

// 计划人数
export const peopleCountPlan = createNumberRule(
  g_t('travelAgency.plannedNumber'),
  g_t('rule.validPeopleCountPlan')
)

// 当前人数
export const peopleCountReal = createNumberRule(
  g_t('travelAgency.currentNumber'),
  g_t('rule.validPeopleCountReal')
)

// 汇率
export const exchangeRate = ({ required = true }) => {
  return createDecimalRule(
    g_t('travelAgency.exchangeRate'),
    g_t('rule.validateExchangeRate'),
    required
  )
}
